package com.example.my_flea_street.controller;

import com.example.my_flea_street.bean.Info;
import com.example.my_flea_street.bean.ResponseModel;
import com.example.my_flea_street.service.impl.EditServiceImpl;
import com.example.my_flea_street.util.ImageUtil;
import com.example.my_flea_street.util.ResponseHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping(value = "/edit")
public class EditController {
    private final EditServiceImpl editService;

    @Autowired
    public EditController(EditServiceImpl editService) {
        this.editService = editService;
    }

    @RequestMapping(value = "/editInfo", method = {RequestMethod.POST, RequestMethod.GET})
    public ResponseEntity<ResponseModel> editInfo(@RequestBody Map<String,String> json) {
        int id = Integer.parseInt(json.get("id"));
        String picBase64 = json.get("pic");
        String text = json.get("text");
        String key_word = json.get("key_word");
        String release_time = json.get("release_time");
        String picUrl = editService.getPic(id);
        if (picBase64.equals(picUrl)) {
            editService.editInfo(id, release_time, text, picUrl, key_word);
            return ResponseHelper.createResponse(0, "成功");
        }
        if (picUrl != null && !picUrl.equals("") && !"null".equals(picUrl))
            ImageUtil.deletePic(picUrl,"info");
        String newPic = "null";
        if (!picBase64.equals(""))
            newPic = ImageUtil.GenerateImage(picBase64,release_time,"info");
        editService.editInfo(id,release_time,text,newPic,key_word);
        return ResponseHelper.createResponse(0,"成功");

    }
    @RequestMapping(value = "/addInfo", method = {RequestMethod.POST, RequestMethod.GET})
    public ResponseEntity<ResponseModel> addInfo(@RequestBody Map<String,String> info) {
        String release_time = info.get("release_time");
        String text = info.get("text");
        int category = Integer.parseInt(info.get("category"));
        int user_id = Integer.parseInt(info.get("user_id"));
        String key = info.get("key");
        System.out.println(text);
        String picBase64 = info.get("pic");
        String newPic = "";
        if (picBase64!=null && !picBase64.equals(""))
            newPic = ImageUtil.GenerateImage(picBase64,release_time,"info");
        editService.addInfo(release_time,text,newPic,category,user_id,key);
        return ResponseHelper.createResponse(0,"成功");
    }
}
